# -*-* encoding:UTF-8 -*-
# author            : mengy
# date              : 2018/12/14
# python-version    : Python 3.7.0
# description       : 会话类

import asynchat
from com.python.demo.mutil_chatting_room.entities.LoginRoom import LoginRoom
from com.python.demo.mutil_chatting_room.entities.LogoutRoom import LogoutRoom
from com.python.demo.mutil_chatting_room.entities.CloseSession import CloseSession


class ChatSession(asynchat.async_chat):
    " 会话类"

    def __init__(self, server, sock):
        asynchat.async_chat.__init__(self, sock)
        self.server = server
        self.set_terminator(b'\n')
        self.data = []
        self.room = None
        self.enter(LoginRoom(server))

    def enter(self, room):
        try:
            print(self.data)
            print(self.server)
            cur = room.do_login(self.server)
        except AttributeError as e:
            print("进入房间异常，异常原因:", e)
            pass
        else:
            room.remove(self)
        self.room = room
        room.add(self)

    def collect_incoming_data(self, data):
        self.data.append(data.encode('utf-8'))

    def found_terminator(self):
        line = ''.join(self.data)
        self.data = []
        try:
            self.room.handle(self, line.encode('utf-8'))
        except CloseSession as e:
            print("发生异常，原因:", e)
            self.handle_close(self)

    def handle_close(self):
        asynchat.async_chat.handle_close(self)
        self.enter(LogoutRoom(self, self.server))
